/**
 * 保存页面请求数据
 */
import md5 from 'js-md5'
import * as cache from '../../util/cache'

// 对应前面三个页面home, category, vip[discount]
// tabbar获取
const homeKey = 'page-home' + md5('home')
const categoryKey = 'page-category' + md5('category')
const vipKey = 'page-vip' + md5('vip')
const tabbarKey = 'page-tabbar' + md5('tabbar')

export default {
  namespaced: true,
  state: {
    home: null,
    category: null,
    vip: null,
    tabbar: null,
  },
  getters: {
    home: state => {
      if (state.home === null) {
        state.home = cache.get(homeKey)
      }
      return state.home
    },
    category: state => {
      if (state.category === null) {
        state.category = cache.get(categoryKey)
      }
      return state.category
    },
    vip: state => {
      if (state.vip === null) {
        state.vip = cache.get(vipKey)
      }
      return state.vip
    },
    tabbar: state => {
      if (state.tabbar === null) {
        state.tabbar = cache.get(tabbarKey)
      }
      return state.tabbar
    }
  },
  mutations: {
    SET_HOME: (state, data) => {
      state.home = data
      cache.save(homeKey, data, 3600 * 12)
    },
    SET_CATEGORY: (state, data) => {
      state.category = data
      cache.save(categoryKey, data, 3600 * 24 * 7)
    },
    SET_VIP: (state, data) => {
      state.vip = data
      cache.save(vipKey, data, 3600 * 2)
    },
    SET_TABBAR: (state, data) => {
      state.tabbar = data
      // 这里不做缓存, 每次都请求
      // 同时可以把缓存时间写入到后台,
      // 这里的时间再根据后台控制操作
      cache.save(tabbarKey, data, 3600 * 24 * 30)
    }
  },
  actions: {
    set_home: ({ commit }, data) => {
      commit('SET_HOME', data)
    },
    set_category: ({ commit }, data) => {
      commit('SET_CATEGORY', data)
    },
    set_vip: ({ commit }, data) => {
      commit('SET_VIP', data)
    },
    set_tabbar: ({ commit }, data) => {
      commit('SET_TABBAR', data)
    }
  }
}
